import { defineStore } from 'pinia'

export const useCaseStore = defineStore('case', {
    state: () => ({
        cases: [],
        loading: false,
        filter: {
            caseNumber: '',
            caseName: '',
            startDate: '',
            endDate: ''
        }
    }),
    actions: {
        async fetchCases(filter = {}) {
            this.loading = true
            try {
                // Use the exposed electronAPI
                if (window.electronAPI) {
                    // Fix: Clone object to remove Vue Proxy/Reactivity before sending via IPC
                    const plainFilter = JSON.parse(JSON.stringify(filter));
                    this.cases = await window.electronAPI.case.getAll(plainFilter)
                } else {
                    console.warn('Electron API not available')
                    this.cases = [] // Mock data could go here
                }
            } catch (error) {
                console.error('Failed to fetch cases:', error)
            } finally {
                this.loading = false
            }
        },
        async createCase(caseData) {
            if (window.electronAPI) {
                await window.electronAPI.case.create(caseData)
                await this.fetchCases()
            }
        },
        async updateCase(caseData) {
            if (window.electronAPI) {
                await window.electronAPI.case.update(caseData)
                await this.fetchCases()
            }
        },
        async deleteCase(caseId) {
            if (window.electronAPI) {
                await window.electronAPI.case.delete(caseId)
                await this.fetchCases()
            }
        }
    }
})
